package org.amse.tanks.controller;

import org.amse.tanks.model.Model;
import org.amse.tanks.model.ModelConstants;
import org.amse.tanks.view.UIView;
import org.amse.tanks.view.UIViewConstants;
import org.amse.tanks.view.View;

import java.io.*;
import java.net.Socket;

public class ClientController implements ModelConstants, UIViewConstants {
    public ClientController(String[] args) {
        int portNumber = 10000;

        if (args.length == 3) {
            portNumber = Integer.parseInt(args[2]);
        } else {
            System.out.println("Wrong parameters");
            System.exit(-1);
        }

        Socket socket = null;
        try {
            socket = new Socket(args[1], portNumber);
        } catch (IOException e) {
            System.err.println("Couldn't get I/O for the connection to host.");
            System.exit(-1);
        }

        InputStream is = null;
        OutputStream os = null;
        ObjectOutputStream oos = null;
        ObjectInputStream ois = null;

        Model model = null;

        try {
            is = socket.getInputStream();
            os = socket.getOutputStream();
            oos = new ObjectOutputStream(os);
            ois = new ObjectInputStream(is);
            model = (Model) ois.readUnshared();
        } catch (IOException e) {
            System.err.println("Couldn't get initial model.");
            System.exit(-1);
        }
        catch (ClassNotFoundException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }

        View view = new UIView(model);
        while (!model.isOver()) {
            String commands = COMMAND_EXIT_CODE;
            commands = view.getStr();

            try {
                oos.writeObject(commands);
            } catch (IOException e) {
                System.err.println("Couldn't send commands.");
                System.exit(-1);
            }

            if (commands.contains(COMMAND_EXIT_CODE)) {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
                }
                System.exit(0);
            }

            try {
                model = (Model) ois.readObject();
            } catch (IOException e) {
                System.err.println("Couldn't get model.");
                System.exit(-1);
            } catch (ClassNotFoundException e) {
                e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
                System.exit(-1);
            }
            view.update(model);
        }

        view.update(null);
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.exit(0);
    }
}